package com.jike.noobmoney.mvp.view.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.image.imagepicker.ImagePicker;
import com.image.imagepicker.bean.ImageItem;
import com.image.imagepicker.ui.ImageGridActivity;
import com.jike.noobmoney.R;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.BuzhouEntity;
import com.jike.noobmoney.mvp.presenter.AppPresenter;
import com.jike.noobmoney.net.IView;
import com.jike.noobmoney.util.Logger;
import com.jike.noobmoney.util.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class StepActivity extends BaseActivity implements IView {


    @BindView(R.id.ll_view)
    LinearLayout llView;

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;

    private AppPresenter appPresenter;
    private ImageView image;

    @Override
    protected int layoutResID() {
        return R.layout.activity_step;
    }

    @Override
    protected void initData() {
        appPresenter = new AppPresenter(this);
        tvTitle.setText("添加步骤");
        tvRight.setText("");

        View view1 = getView();
        addView(view1);
        addEvent(view1);

    }

    View xkview;

    private void addEvent(View view) {

        TextView tvRemoveView = (TextView) view.findViewById(R.id.tv_remove_view);
        TextView tvAddView = (TextView) view.findViewById(R.id.tv_add_view);
        ImageView ivPic = (ImageView) view.findViewById(R.id.iv_pic);


        tvRemoveView.setOnClickListener(v -> {
            if (llView.getChildCount() == 1) {
                ToastUtils.showShortToastSafe("至少需要添加1步");
                return;
            }
            removeView(view);
        });

        tvAddView.setOnClickListener(v -> {
            if (llView.getChildCount() > 3) {
                ToastUtils.showShortToastSafe("最多只能添加4步");
                return;
            }

            View view2 = getView();
            addView(view2);
            addEvent(view2);
        });

        ivPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xkview = v;
                ImagePicker.getInstance().setSelectLimit(1);
                ImagePicker.getInstance().setCrop(false);
                ImagePicker.getInstance().setShowCamera(true);
                ImagePicker.getInstance().setMultiMode(true);
                Intent intent1 = new Intent(context, ImageGridActivity.class);
                startActivityForResult(intent1, 100);
            }
        });
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == 100) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    image = xkview.findViewById(R.id.iv_pic);
                    //image.setImageResource(R.mipmap.ic_launcher);
                    Logger.e("xuke", "--->" + images.get(0));

                    showProgress();
                    appPresenter.upload(new File(images.get(0).getPath()), ConstantValue.RequestKey.uploadfile);

                }
            }
        }
    }


    private View getView() {
        LayoutInflater inflater = LayoutInflater.from(this);
        return inflater.inflate(R.layout.item_add_layout, null);
    }

    private void addView(View layout) {
        llView.addView(layout);
    }

    private void removeView(View layout) {
        llView.removeView(layout);
    }


    private List<BuzhouEntity> students = new ArrayList<>();

    private void printText() {
        for (int i = 0; i < llView.getChildCount(); i++) {
            View view = llView.getChildAt(i);
            EditText etText = (EditText) view.findViewById(R.id.et_text);
            ImageView ivPic = (ImageView) view.findViewById(R.id.iv_pic);
            CheckBox cbCheck = (CheckBox) view.findViewById(R.id.cb_check);
            BuzhouEntity student = new BuzhouEntity();
            student.setStep_text(etText.getText().toString().trim());
            student.setStep_pic("" + ivPic.getTag());
            student.setFlag(cbCheck.isChecked() ? "1" : "0");
            ivPic.setTag(null);
            students.add(student);
        }
        String jsonStr = new Gson().toJson(students);
        Logger.e("xuke", "json = " + jsonStr);

        Intent intent = new Intent();
        intent.putExtra("step", jsonStr);
        setResult(RESULT_OK, intent);

//        for (int i = 0; i < llView.getChildCount(); i++) {
//            View view = llView.getChildAt(i);
//            ImageView ivPic = (ImageView) view.findViewById(R.id.iv_pic);
//            ivPic.setTag(null);
//        }
        finish();
    }

    @OnClick({R.id.iv_back, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_sure:
                if (isPre()) {
                    printText();
                }
                break;
        }
    }

    private boolean isPre() {
        for (int i = 0; i < llView.getChildCount(); i++) {
            View view = llView.getChildAt(i);
            EditText etText = (EditText) view.findViewById(R.id.et_text);
            ImageView ivPic = (ImageView) view.findViewById(R.id.iv_pic);
            String trim = etText.getText().toString().trim();
            String tag = "" + ivPic.getTag();
            if (TextUtils.isEmpty(trim) || TextUtils.isEmpty(tag)) {
                ToastUtils.showShortToastSafe("请填写步骤说明并且上传示例图片");
                return false;
            }
        }
        return true;
    }

    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        dismissProgress();
        if (ConstantValue.RequestKey.uploadfile.equals(actionType)) {
            String url = (String) data;
            if (image != null) {
                image.setTag(null);
                Glide.with(this).load(ConstantValue.IMG_BASEURL + url).into(image);
                image.setTag(url);
            }

        }
    }

    @Override
    public void onFailed(String code, String msg) {
        dismissProgress();
    }

    @Override
    protected void onDestroy() {
        if (image != null) {
            image.setTag(null);
        }
        super.onDestroy();
    }
}
